package fileupload;


import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

import java.io.File;
import org.apache.struts2.json.annotations.*;

public class UploadAction extends ActionSupport{

	//上传文件,transient标记的属性不会被序列化
	private transient File upload;
	//上传文件名
	private transient String uploadFileName;
	//上传文件内容类型
	private transient String uploadContentType;
	//保存路径
	private transient String savePath;
	//生成文件名的工具
	private transient MakeFileNameService fileNameMaker;
	//文件后缀名
	private transient String allownFileExt;
	//文件大小限制
	private transient String maxFileSize;
	//文件上传后的服务器路径及名字
	private String savedFileName;
	//处理结果状态标记，1表示成功，0表示失败
	private Integer state=0;
	//处理结果消息，可以用于前台显示错误消息
	private String errorMsg="";
	public String getSavePath() {
	   return savePath;
	}
	public void setSavePath(String savePath) {
	   this.savePath = savePath;
	}
	   
	public File getUpload() {
	   return upload;
	}
	public void setUpload(File upload) {
	   this.upload = upload;
	}

	public String getUploadFileName() {
	   return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
	   this.uploadFileName = uploadFileName;
	}
	public String getUploadContentType() {
	   return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
	   this.uploadContentType = uploadContentType;
	}
	public MakeFileNameService getFileNameMaker()
	{
		return this.fileNameMaker;
	}
	public void setFileNameMaker(MakeFileNameService makeFileNameService)
	{
		this.fileNameMaker=makeFileNameService;
	}
	public String getAllownFileExt()
	{
		return this.allownFileExt;
	}
	public void setAllownFileExt(String allownFileExt)
	{
		this.allownFileExt=allownFileExt;
	}
	public String getMaxFileSize()
	{
		return this.maxFileSize;
	}
	public void setMaxFileSize(String maxFileSize)
	{
		this.maxFileSize=maxFileSize;
	}
	@JSON(name="savedfilename")
	public String getSavedFileName()
	{
		return this.savedFileName;
	}	
	public void setSavedFileName(String savedFileName)
	{
		this.savedFileName=savedFileName;
	}
	@JSON(name="state")
	public Integer getState()
	{
		return this.state;
	}
	public void setState(Integer state)
	{
		this.state=state;
	}
	@JSON(name="errormsg")
	public String getErrorMsg()
	{
		return this.errorMsg;
	}
	public void setErrorMsg(String errorMsg)
	{
		this.errorMsg=errorMsg;
	}
	/*
	 * 验证上传文件类型是否合法
	 * @param ext 上传文件的后缀名
	 * @return 若合法，返回true；否则，返回false
	 */
	private boolean isValidFileExtention(String ext)
	{
		boolean valid=false;
		//没有对后缀名进行限制
		if(this.getAllownFileExt()==null||
				this.getAllownFileExt().equals("")||
				this.getAllownFileExt().equals(ext))
			return true;
		//配置中提供的后缀名使用,分隔
		String[] exts=this.getAllownFileExt().split(",");
		if(exts==null||exts.length<=0)
			return false;
		for(int i=0;i<exts.length;i++)
		{
			if(exts[i].equals(ext))
			{
				return true;
			}
		}
		return valid;
	}
	/*
	 * 验证上传文件大小是否符合限制
	 * @param fileSize 上传文件的大小
	 * @return 若小于允许值，返回true；否则，返回false
	 */
	public boolean isValidFileSize(long fileSize)
	{
		String defaultMaxFileSize="2097152";//默认2M//DefaultSettings.get(StrutsConstants.STRUTS_MULTIPART_MAXSIZE);
		//若未配置文件大小限制，则使用系统的默认大小值
		if(this.getMaxFileSize()==null||this.getMaxFileSize().equals(""))
			this.setMaxFileSize(defaultMaxFileSize);
		//若未对默认的文件大小做限制，则不允许上传
		if(defaultMaxFileSize==null||defaultMaxFileSize.equals(""))
			return false;
		long maxSize=Long.parseLong(getMaxFileSize());
		if(fileSize>maxSize)
			return false;
		else
			return true;
	}
	@Override
	public String execute() throws Exception {
		//若没有上传文件，异常退出
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		WebApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
		fileNameMaker=(MakeFileNameService)ctx.getBean("filenamemaker");
		if(getUpload()==null)
		{
			this.state=0;
			this.errorMsg="please choose file to upload!";
			return Action.NONE;	
		}
		
		//获取文件后缀名
		String ext="";
		if(getUploadFileName().lastIndexOf(".")!=-1)
			ext=getUploadFileName().substring(getUploadFileName().lastIndexOf(".")+1).toLowerCase();
		//验证后缀名是否合法
		if(!this.isValidFileExtention(ext))
		{
			this.state=0;
			this.errorMsg="file type is not allown!";
			return Action.NONE;
		}
		
		FileInputStream fis=new FileInputStream(getUpload());
		long fileSize=fis.available();
		//验证文件大小是否合法
		if(!this.isValidFileSize(fileSize))
		{
			this.state=0;
			this.errorMsg="uploaded file is too large!the filesize is limited to "+Integer.parseInt(this.maxFileSize)/(1024*1024)+"M";
			return Action.NONE;
		}
		//按指定业务规则生成目标文件名
		String rootPath = ServletActionContext.getServletContext().getRealPath("/"); 
		
		String destinFileName=getUploadFileName();
		if(this.getFileNameMaker()!=null)
			destinFileName=getFileNameMaker().MakeFileName(getUploadFileName(), ext);
		String targetFile=rootPath+getSavePath()+"\\"+destinFileName;
		
		FileOutputStream fos=new FileOutputStream(targetFile);	    
	    byte[] buffer=new byte[1024];
	    int len=0;
	    while((len=fis.read(buffer))>0)
	    {
	    	fos.write(buffer,0,len);
	    }
	    this.state=1;
	    this.savedFileName=ServletActionContext.getServletContext().getContextPath()+"\\"+destinFileName;
	    return Action.SUCCESS;
	}
	
}

